package com

import (
	model "beergo/app/sys/models"
	"beergo/conf/const/code"
	"beergo/lib/base/controller"
	"beergo/lib/event"
	"beergo/lib/tool"
	"encoding/base64"
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"time"
)

type LoginController struct {
	controller.ContainerController
	UserRepository *model.UserRepository
	UserModel      *model.User
	JsonData       map[string]interface{}
}

func (this *LoginController) Prepare() {
	this.UserRepository = new(model.UserRepository)
	this.UserModel = new(model.User)
	this.JsonData = map[string]interface{}{}
}

func init() {
	web.Router("/login", &LoginController{}, "GET,POST:LoginAction")
	web.Router("/logout", &LoginController{}, "GET,POST:LogoutAction")
	web.Router("/PasswordChange", &LoginController{}, "GET,POST:PasswordChangeAction")
}

func (this *LoginController) LoginAction() {
	username := this.GetParamString("username")
	if username == "" {
		this.ReturnError(code.Error, "请输入账号", "")
		this.StopRun()
	}
	password := this.GetParamString("password")
	if password == "" {
		this.ReturnError(code.Error, "请输入密码", "")
		this.StopRun()
	}
	find := this.UserRepository.FindOneBy(tool.StringKeyMap{"phone": username}, nil)
	if find.Id == 0 {
		find = this.UserRepository.FindOneBy(tool.StringKeyMap{"account": username}, nil)
	}

	if find.Id == 0 {
		//todo 记录尝试次数

		this.ReturnError(code.Error, "账号错误", "")
		this.StopRun()
	}
	if find.Password != password {
		//todo 记录尝试次数

		this.ReturnError(code.Error, "密码错误", "")
		this.StopRun()
	}
	vi:=web.AppConfig.DefaultString("vi","123456")
	token := tool.AesEncrypt(fmt.Sprintf("user %d vi %d",find.Id,time.Now().Unix()),vi)
	tk:=base64.StdEncoding.EncodeToString([]byte(token))
	println(tk)
	find.Token = tk
	find.Save()
	err:=this.SetCache("user",find)
	this.AnaliseErrors(err)
	//find标识账号信息，
	this.JsonData["account"] = find
	//发出登录事件，需要处理的监听器在JsonData中添加个系统的返回
	event.DispatchToMany("Login", this.JsonData,this.Ctx)
	//this.JsonData["account"] =  find
	this.ReturnSuccess("登录成功", this.JsonData)
}

func (this *LoginController) LogoutAction() {
	u,e:=this.GetCache("user")
	if e != nil {
		println(e.Error())
	}
	user := this.GetUser()
	if user.Id != 0 {
		user.Token = ""
		_,err:=user.Save()
		if err != nil {
			this.AnaliseErrors(err)
		}
		//todo 发出socket关闭命令
		event.DispatchToMany("Logout", user,this.Ctx)
	}
	this.ReturnSuccess("已退出", u)
}


func (this *LoginController) PasswordChangeAction() {
	old:=this.GetParamString("old")
	pswnew:=this.GetParamString("new")
	pswag:=this.GetParamString("ag")
	user := this.GetUser()
	if user.Id == 0 {
		this.ReturnError(code.ErrorAuth,"请登录后再操作","1")
		this.StopRun()
	}
	if user.Password != old {
		this.ReturnError(code.Error,"密码错误","1")
		this.StopRun()
	}
	if pswnew != pswag {
		this.ReturnError(code.Error,"两次输入不一致","1")
		this.StopRun()
	}
	user.Password = pswnew
	_,err:=user.Save()
	this.AnaliseErrors(err)
	this.ReturnSuccess("更新成功", "")
}
